package com.hz.filemanager.ui.file;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.core.widget.ContentLoadingProgressBar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.hz.filemanager.R;
import com.hz.filemanager.ad.utils.AnalyticsUtils;
import com.hz.filemanager.model.DialogManager;
import com.hz.filemanager.ui.base.BaseActivity;
import com.hz.filemanager.ui.file.adapter.DownloadAdapter;
import com.hz.filemanager.ui.file.adapter.OnRVItemClickListener;
import com.hz.filemanager.utils.FileUtils;
import com.kathline.library.util.ZFileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DownloadActivity extends BaseActivity implements OnRVItemClickListener {

    private View statusBarDimen;
    private RelativeLayout All;
    private Toolbar toolbar;
    private CheckedTextView ctAll;
    private RecyclerView rv;
    private ContentLoadingProgressBar loading;
    private LinearLayout modifyLl;
    private TextView renameTv;
    private TextView deleteTv;
    private SwipeRefreshLayout refreshLayout;
    private LinearLayout emptyLayout;

    private DownloadAdapter downloadAdapter;

    //本页面仅展示某个文件夹下的文件，修改此路径以展示不同路径下的文件
    private String DOWNLOAD_PATH = "/sdcard/Download";
    private List<File> files = FileUtils.listFilesInDir(DOWNLOAD_PATH, false);


    @Override
    protected int getLayoutId() {
        return R.layout.activity_download;
    }

    @Override
    protected void initView() {
        AnalyticsUtils.INSTANCE.logEvent("ckdownloads");
        statusBarDimen = (View) findViewById(R.id.status_bar_dimen);
        All = (RelativeLayout) findViewById(R.id.All);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        ctAll = (CheckedTextView) findViewById(R.id.cb_all_toolbar);
        rv = (RecyclerView) findViewById(R.id.rv);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
        modifyLl = (LinearLayout) findViewById(R.id.modify_ll);

        renameTv = (TextView) findViewById(R.id.rename_tv);
        deleteTv = (TextView) findViewById(R.id.delete_tv);
        emptyLayout = (LinearLayout) findViewById(R.id.emptyLayout);

        setSupportActionBar(toolbar);
    }

    @Override
    protected void initEvent() {

        toolbar.setTitle(getString(R.string.download));
        downloadAdapter = new DownloadAdapter(DownloadActivity.this, files, this);
        rv.setLayoutManager(new LinearLayoutManager(DownloadActivity.this));
        rv.setAdapter(downloadAdapter);
        refreshLayout.setEnabled(false);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDataAndReset();
            }
        });

        ctAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //勾选
                ctAll.toggle();
                if (ctAll.isChecked()) {
                    downloadAdapter.checkAllOf(true);
                } else {
                    downloadAdapter.checkAllOf(false);
                }
                checkState();
            }
        });

        renameTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DialogManager.renameDialog(DownloadActivity.this,
                        downloadAdapter.getSelectedFiles().get(0).getAbsolutePath(),
                        downloadAdapter.getSelectedFiles().get(0).getName(),
                        new DialogManager.OnRenameListener() {
                            @Override
                            public void onSuccess(String newName, String newPath) {
                                getDataAndReset();

                                //showToast("Rename Success");
                            }

                            @Override
                            public void onFailed() {
                                showToast("Rename Failure");
                            }
                        });
            }
        });

        deleteTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DialogManager.deleteFileDialog(DownloadActivity.this, new DialogManager.OnDialogClickListener() {
                    @Override
                    public void onOKClick(Object data) {
                        final List<File> deleteFiles = downloadAdapter.getSelectedFiles();
                        final ArrayList<String> deleteFilePath = new ArrayList<>();
                        for (File deleteFile : deleteFiles) {
                            if (deleteFile.delete()) {
                                deleteFilePath.add(deleteFile.getAbsolutePath());
                            }
                        }
                        notifyFileIsDeleted(deleteFilePath);
                        getDataAndReset();
                        //showToast("Delete for " + deleteFilePath.size() + " item");
                    }
                });
            }
        });
    }

    private void getDataAndReset() {
        refreshLayout.setRefreshing(true);
        files = FileUtils.listFilesInDir(DOWNLOAD_PATH, false);
        downloadAdapter.resetData(files);
        downloadAdapter.setSelectMode(false);
        updateSelectMode();
        refreshLayout.setRefreshing(false);
    }

    @Override
    public void onClick(View view, int position, File file, Boolean isCheck) {
        Log.e("点击条目", position + file.getAbsolutePath() + isCheck);
        if (!downloadAdapter.isSelectMode()) {
            if (file.isDirectory()) {

                if(file.list().length > 0){
                    refreshLayout.setRefreshing(true);
                    files = FileUtils.listFilesInDir(file.getAbsolutePath(), false);
                    DOWNLOAD_PATH = file.getAbsolutePath();
                    downloadAdapter.resetData(files);
                    refreshLayout.setRefreshing(false);
                }
            }else{
                ZFileUtil.openFile( file.getAbsolutePath(), view);
            }
        } else {
            checkState();
        }
    }

    @Override
    public void onLongClick() {
        if (downloadAdapter != null && !downloadAdapter.isSelectMode()) {
            downloadAdapter.setSelectMode(true);
            updateSelectMode();
            checkState();
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                //选择状态下，点击左上角 x 取消选中模式
                //清空已选择数据 恢复勾选数据 导航重置为返回键
                if (downloadAdapter.isSelectMode()) {
                    downloadAdapter.setSelectMode(false);
                    updateSelectMode();
                } else {
                    //非选择状态，结束
                    finish();
                }
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        //选择状态下，点击左上角 x 取消选中模式
        //清空已选择数据 恢复勾选数据 导航重置为返回键
        if (downloadAdapter.isSelectMode()) {
            downloadAdapter.setSelectMode(false);
            updateSelectMode();
        } else if (DOWNLOAD_PATH.split("/").length > 3) {//当路径仅剩sdcard/download就不再展示上一层的数据了
            emptyLayout.setVisibility(View.GONE);
            refreshLayout.setRefreshing(true);
            //拿到当前展示路径的父路径
            DOWNLOAD_PATH = new File(DOWNLOAD_PATH).getParent();
            //拿到父路径的所有文件
            files = FileUtils.listFilesInDir(new File(DOWNLOAD_PATH),false);
            //重新设置数据
            downloadAdapter.resetData(files);
            refreshLayout.setRefreshing(false);
        } else {
            //非选择状态，结束
            super.onBackPressed();
        }
    }

    private void updateSelectMode() {
        if (downloadAdapter.isSelectMode()) {
            modifyLl.setVisibility(View.VISIBLE);
            ctAll.setVisibility(View.VISIBLE);
            toolbar.setNavigationIcon(getDrawable(R.mipmap.cancle));
        } else {
            modifyLl.setVisibility(View.GONE);
            ctAll.setVisibility(View.GONE);
            toolbar.setNavigationIcon(getDrawable(R.mipmap.back));
        }
    }

    private void checkState() {
        if (files != null && files.size() == 0) {
            emptyLayout.setVisibility(View.VISIBLE);
        } else {
            emptyLayout.setVisibility(View.GONE);
        }
        if (downloadAdapter.getSelectedFiles() == null) return;
        if (downloadAdapter.getSelectedFiles().size() == 1) {
            renameTv.setEnabled(true);
        } else {
            renameTv.setEnabled(false);
        }
        if (downloadAdapter.getSelectedFiles().size() == 0) {
            deleteTv.setEnabled(false);
        } else {
            deleteTv.setEnabled(true);
        }
    }
}